package es.capgemini.extjsplugin.wizard;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.core.PackageFragment;
import org.eclipse.jdt.ui.IJavaElementSearchConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ContainerSelectionDialog;
import org.eclipse.ui.dialogs.SelectionDialog;

import es.capgemini.extjsplugin.core.Utils;
import es.capgemini.extjsplugin.ui.ClassSelectionPanel;

public class ClassSelectionPage extends WizardPage implements Listener{
	

	private GeneratorWizardModel model;
	private ClassSelectionPanel panel;
	private IStatus selectedClassStatus;
	
	public ClassSelectionPage(String pagename){
		super(pagename);
		setTitle("Entidad");
		setDescription(" Seleccionar Clase, paquete destino, y carpeta para web de la cual se desea generar Formularios");
	}
	@Override
	public void createControl(Composite parent) {
		panel = new ClassSelectionPanel(parent,SWT.EMBEDDED);
		setControl(panel);
		addListeners();
		setPageComplete(false);

	}
	@Override
	public void handleEvent(Event evt) {
		 // Initialize a variable with the no error status
	     Status status = new Status(IStatus.OK, "not_used", 0, "", null);

		if(evt.widget==panel.getClassSelectionButton()){
			try {
				seleccionarClase();
			} catch (Exception e) {
				//e.printStackTrace();
				status = new Status(IStatus.ERROR, "not_used", 0, 
						e.getMessage(), null);
				
			}
		}
		if(evt.widget==panel.getWebFolderSelectButton()){
			seleccionarWebFolder();
		}
		if(evt.widget==panel.getPackageSelectionButton()){
			selecccionarPackage();
		}
		applyToStatusLine(status);
		getWizard().getContainer().updateButtons();
	}
	
	private void addListeners(){
		panel.getClassSelectionButton().addListener(SWT.Selection, this);
		panel.getWebFolderSelectButton().addListener(SWT.Selection, this);
		panel.getPackageSelectionButton().addListener(SWT.Selection, this);
		panel.getSelectedClassName().addListener(SWT.KeyUp, this);
		panel.getPaquete().addListener(SWT.KeyUp, this);
		panel.getWebFolder().addListener(SWT.KeyUp, this);
	}
	@Override
	public IWizardPage getNextPage() {
		saveDataToModel();
		AttributesSelectionPage page=((GeneratorWizard)getWizard()).attributesSelectionPage;
		//ComponentSelectionPage page=((GeneratorWizard)getWizard()).componentSelectionPage;
		page.onEnterPage();
		return page;
	}
	/*
	 * Saves the uses choices from this page to the model.
	 * Called on exit of the page
	 */
	private void saveDataToModel(){
		 // Gets the model
		GeneratorWizard wizard = (GeneratorWizard)getWizard();
		model = wizard.model;
		model.setMyClass(panel.getSelectedClass());
		model.setPackage_url(panel.getPackage_url());
		model.setPackage_name(panel.getPackageName());
		model.setWeb_folder(panel.getWebFolderPath());
	}
	
	@Override
	public boolean canFlipToNextPage() {
		return panel.getSelectedClass()!=null && 
			panel.getPackageName()!=null && panel.getPackageName()!="" &&
			panel.getWebFolderPath()!=null && panel.getWebFolderPath()!="";
	}

	
	private void seleccionarClase() throws Exception{
		try {
			Class myClass=null;
			IRunnableContext context = PlatformUI.getWorkbench().getProgressService();
			IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
			SelectionDialog dialog = JavaUI.createTypeDialog(
			        getShell(), context,
			        scope,
			        IJavaElementSearchConstants.CONSIDER_CLASSES, false);
			
			if (dialog.open() == IDialogConstants.CANCEL_ID)
			      return;
			Object[] types= dialog.getResult();
			if (types == null || types.length == 0)
				return;
			
			IType selectedClass=((IType)types[0]);
			myClass=Utils.loadClass(selectedClass);
			if(myClass==null)
				throw new Exception("No se pudo obtener la clase. Revise la compilacion del proyecto");
			String package_path=selectedClass.getResource().getLocation().toOSString();
			String file=selectedClass.getResource().getLocation().lastSegment();
			package_path=package_path.split(file)[0];
			
			panel.setSelectedClass(myClass);
			panel.getSelectedClassName().setText(myClass.getName());
			panel.setPackageName(myClass.getPackage().getName());
			panel.getPaquete().setText(myClass.getPackage().getName());
			panel.setPackage_url(package_path);
			((GeneratorWizard)getWizard()).model.addProject(selectedClass.getJavaProject().getProject());
			((GeneratorWizard)getWizard()).model.setPackageFragment(selectedClass.getPackageFragment());
			
		} catch (JavaModelException e) {
			e.printStackTrace();
		}
		
	}
	@SuppressWarnings({ "restriction", "deprecation" })
	private void selecccionarPackage() {
		IRunnableContext context = PlatformUI.getWorkbench().getProgressService();
		//IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
		IProject projects[]=ResourcesPlugin.getWorkspace().getRoot().getProjects();
		IJavaSearchScope scope= SearchEngine.createJavaSearchScope(projects);
		
		//scope=SearchEngine.createHierarchyScope(IType);
		SelectionDialog dialog;
		
		dialog = JavaUI.createPackageDialog(getShell(), context, scope, false, true, null);
//		dialog = JavaUI.createPackageDialog(
//		 							getShell(),
//		 							javaProject,
//		 							IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS
//		 						);

		
		if (dialog.open() == IDialogConstants.CANCEL_ID)
		      return;
		Object[] types= dialog.getResult();
		if (types == null || types.length == 0)
			return;
		
		PackageFragment packageFragment=((PackageFragment)types[0]);
		String package_path=packageFragment.getElementName();
		panel.getPaquete().setText(package_path);
		panel.setPackage_url(package_path);
		((GeneratorWizard)getWizard()).model.addProject(packageFragment.getJavaProject().getProject());
		((GeneratorWizard)getWizard()).model.setPackageFragment(packageFragment);
		
		
	}
	/**
	 * Applies the status to the status line of a dialog page.
	 */
	private void applyToStatusLine(IStatus status) {
		String message= status.getMessage();
		if (message.length() == 0) message= null;
		switch (status.getSeverity()) {
			case IStatus.OK:
				setErrorMessage(null);
				setMessage(message);
				break;
			case IStatus.WARNING:
				setErrorMessage(null);
				setMessage(message, WizardPage.WARNING);
				break;				
			case IStatus.INFO:
				setErrorMessage(null);
				setMessage(message, WizardPage.INFORMATION);
				break;			
			default:
				setErrorMessage(message);
				setMessage(null);
				break;		
		}
	}
	private void seleccionarWebFolder() {	

			ContainerSelectionDialog dialog= new ContainerSelectionDialog(getShell(), null, true, "Select a parent:");
			dialog.setTitle("Container Selection");
			dialog.open();
			
		
			IPath path=(IPath)dialog.getResult()[0];
			String workspacePath=ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString();
			String webFolderPath=path.toString();
			if (webFolderPath==null)
			      return;
			panel.getWebFolder().setText(workspacePath+webFolderPath);
			panel.setWebFolderPath(workspacePath+webFolderPath);
			
			((GeneratorWizard)getWizard()).model.addProject(ResourcesPlugin.getWorkspace().getRoot().findMember(path).getProject());
				
		
	}	

}
